package com.study.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BioServer {
    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        ServerSocket serverSocket = new ServerSocket(2881);
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("新客户端连接：");
            executorService.execute(new ReceiveMsg(socket));
        }
    }

    private static class ReceiveMsg implements Runnable {

        private Socket socket;

        public ReceiveMsg(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            BufferedReader br = null;
            PrintWriter pw = null;
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                pw = new PrintWriter(socket.getOutputStream());
                String msg = "";
                while (!"886".equals(msg = br.readLine())) {
                    System.out.println("客户端说：" + msg);
                    msg = "Server: " + msg + ", Now is " + new Date().toString();
                    pw.println(msg);
                    pw.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (pw != null)
                    pw.close();
            }
        }
    }
}
